package com.yjkf.zh.admin.config;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.iot.api.message.MessageClientFactory;
import com.aliyun.openservices.iot.api.message.api.MessageClient;
import com.aliyun.openservices.iot.api.message.callback.MessageCallback;
import com.aliyun.openservices.iot.api.message.entity.Message;
import com.aliyun.openservices.iot.api.message.entity.MessageToken;
import com.yjkf.zh.admin.dao.SysDeviceEventMapper;
import com.yjkf.zh.admin.dao.SysDeviceMapper;
import com.yjkf.zh.admin.dao.SysProductMapper;
import com.yjkf.zh.admin.model.SysDevice;
import com.yjkf.zh.admin.model.SysDeviceEvent;
import com.yjkf.zh.admin.model.SysProduct;
import com.yjkf.zh.admin.model.aliyunIot.DevicePropertyPost;
import com.yjkf.zh.admin.util.PojoUtil;
import com.yjkf.zh.admin.util.SysConstant;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import com.aliyun.openservices.iot.api.Profile;
import org.springframework.context.annotation.Configuration;

import java.util.List;

//@Configuration
public class DeviceMessageRegister implements InitializingBean {

   // private String accessKey="LTAI15a7DBp6ScmD";

    private String accessKey= "LTAI4FteAmT72WrKLJkj5QdV";

    private String accessSecret="O3PxeWvPTHajKwwZ4AS4JlfRSFe98C";

    //private String accessSecret="oLSe0uvSamvGQvMEmN2hAGawdJ4W4g";


    private String regionId="cn-shanghai";

   // private String uid="1874858313601505";
    private String uid="1150762710362502";


   // private String productKey="a1UTv0vmM7k";

  //  private String productKey="a1jhwQkAWDQ";

    private String productKey="a1Gz1TFwIDv";

//    @Autowired
 //   private SysUserMapper sysUserMapper;

    @Autowired
    private SysProductMapper sysProductMapper;

    @Autowired
    private SysDeviceMapper sysDeviceMapper;

    @Autowired
    private SysDeviceEventMapper sysDeviceEventMapper;

    @Autowired
    private Topic topic;

    @Override
    public void afterPropertiesSet() throws Exception {

        String endPoint = "https://" + uid + ".iot-as-http2." + regionId + ".aliyuncs.com";
        // 连接配置
       Profile profile = Profile.getAccessKeyProfile(endPoint, regionId, accessKey, accessSecret);
        System.out.println(profile+":");
        // 构造客户端
        MessageClient client = MessageClientFactory.messageClient(profile);
        client.setMessageListener(new MessageCallback() {
            @Override
            public Action consume(MessageToken messageToken) {
                return null;
            }
        });
        //属性上报  topic:   /productKey/#/thing/event/property/post
/*   client.setMessageListener(topic.getDevicePropertyPostTopic(), new MessageCallback() {
            @Override
            public Action consume(MessageToken messageToken) {
                Message m = messageToken.getMessage();
               // logger.info("receive 属性上报" + new String(messageToken.getMessage().getPayload()));
                DevicePropertyPost devicePropertyPost = JSON.parseObject(new String(m.getPayload()), DevicePropertyPost.class);

                    //根据productKey获取deviceId
                SysProduct sysProduct = sysProductMapper.selectForProductKey(productKey);
                List<SysDevice> sysDeviceList=sysDeviceMapper.findDeviceForProductId(sysProduct.getId());   //根据产品id获取设备列表
                System.out.println(1);
               for(SysDevice sysDevice:sysDeviceList) {                 //循环设备列表
                   List<SysDeviceEvent> sysDeviceEventList = sysDeviceEventMapper.findDeviceEventPage(1, 2);    //根据设备Id 获取事件列表
                   for (SysDeviceEvent sysDeviceEvent : sysDeviceEventList) {      //遍历事件列表
                       System.out.println(2);
                       //获取事件的上下限与数值
                       if ("<".equals(sysDeviceEvent.getEventRule())) {
                           DevicePropertyPost.Data data = new DevicePropertyPost.Data();
                           if (PojoUtil.isExistField(sysDeviceEvent.getPointIdent(), data) != null) {
                               if (sysDeviceEvent.getCount() > (Integer) PojoUtil.isExistField(sysDeviceEvent.getPointIdent(), data)) {
                                   System.out.println(sysDeviceEvent);
                               }
                           }

                       }
                   }
               }
                   return Action.CommitSuccess;
            }});*/
        //属性上报  topic:   /productKey/#/thing/event/property/post
        client.setMessageListener(topic.getDevicePropertyPostTopic(), new MessageCallback() {
            @Override
            public Action consume(MessageToken messageToken) {
                Message m = messageToken.getMessage();
                DevicePropertyPost devicePropertyPost = JSON.parseObject(new String(m.getPayload()), DevicePropertyPost.class);

                System.out.println(devicePropertyPost.getItems().getChannel01());
                    return Action.CommitSuccess;

               }});




        // 数据接收
        client.connect(messageToken -> {
            Message m = messageToken.getMessage();
            byte[] payload = m.getPayload();
            System.out.println("receive message from " + m);
            System.out.println("m.getTopic() = " + m.getTopic());
            return MessageCallback.Action.CommitSuccess;
        });


    }


}
